import { createPrePayOrder } from '@/api/pay'

const getPrepayOrder = async (orderNo, wxCode) => {
  let orderInfo = {}
  const { code , data, msg } = await createPrePayOrder({
    orderNum: orderNo,
    payType: 'WXAPP_PAY',
    code: wxCode
  })
  if (code === '1') {
    try {
      orderInfo = JSON.parse(data.payStr)
    } catch(err) {
      console.error(err)
    }
    const paymentObject = {
      timeStamp: orderInfo.timeStamp,
      nonceStr: orderInfo.nonceStr,
      package: orderInfo.package,
      signType: orderInfo.signType,
      paySign: orderInfo.paySign,
      success() {
        uni.redirectTo({ url: '/pages/pay/payResult?orderNo=' + orderNo })
      },
      fail(err) {
        console.error('pay_result: ' + err.errMsg)
        if (err.errMsg === 'requestPayment:fail cancel') {
          // 取消支付
          uni.showToast({
            title: '取消支付',
            icon: 'none',
          })
        } else {
          uni.showToast({
            title: err.errMsg,
            icon: 'none',
          })
        }
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/jianding/list' })
        }, 500)
      },
      complete() {
        uni.hideLoading()
      }
    }
    wx.requestPayment(paymentObject)
  } else {
    uni.showToast({ icon: "none", title: msg })
  }
}

export default {
  getPrepayOrder
}
